#!/usr/bin/python3

import os
import pathlib
import time
import csv
import datetime




def run_power():
    os.system('ssh -f agent1 "cd /home/shy/; mpstat 1 > mpstat_server.txt &"')
    os.system('ssh -f agent1 "cd /home/shy/; sh show_power.sh &"')

    # os.system('sh show_power.sh &')
    # os.system('mpstat 1 > mpstat_client.txt &')


def get_server_data():
    os.system('ssh -f agent1 "cd /home/shy; sh kill_mpstat.sh"')
    os.system('ssh -f agent1 "cd /home/shy; sh kill_power.sh"')
    # os.system("sh kill_mpstat.sh")
    # os.system("sh kill_power.sh")
    os.system("rm -f mpstat_server.txt")
    os.system("rm -f power.txt")

    path = pathlib.Path("mpstat_server.txt")
    for i in range(5):
        if not path.is_file():
            print("no mpstat.txt")
            os.system("scp agent1:/home/shy/mpstat_server.txt ./mpstat_server.txt")
            time.sleep(1)
        else:
            break
    path = pathlib.Path("power.txt")
    for i in range(5):
        if not path.is_file():
            print("no power.txt")
            os.system("scp agent1:/home/shy/power.txt ./power.txt")
            time.sleep(1)
        else:
            break


# def delete_client_data():
#     os.system("rm -rf mpstat_client.txt")
#     os.system("rm -rf power_client.txt")
#     '''
#     删除客户端的文件, 程序再次执行会有新的文件生成，避免有以前文件的数据
#     '''
def get_avg_util(mpstat_file) -> float:
    util = []
    avg_util = 0
    with open(mpstat_file, "r") as f:
        for line in f.readlines():
            if "all" in line:
                util.append(100 - float(line.strip().split()[-1]))
    if len(util) > 0:
        avg_util = sum(util) / len(util)
    return avg_util


def get_avg_power(power_file) -> float:
    power = []
    avg_power = 0
    with open(power_file, "r") as f:
        for line in f.readlines():
            power.append(int(line.strip().split()[-1]))
    if len(power) > 0:
        avg_power = sum(power) / len(power)
    return avg_power


def write_csv(governor: str, server_power: float, server_util: float, client_power: float,
              client_util: float,tpcc_score: float):
    with open("./result.csv", 'a', newline='') as f:
        csv_write = csv.writer(f)
        # csv_write.writerow(header)
        row = []
        row.append(governor)

        row.append(f'{server_power:.3f}')
        row.append(f'{server_util:.3f}')

        row.append(f'{client_power:.3f}')
        row.append(f'{client_util:.3f}')
        row.append(f'{tpcc_score:.3f}')
        #
        csv_write.writerow(row)


def run_mysql_tpcc():
    print("run %s time" % count)
    current_dir = os.getcwd()
    path = "/home/shy/benchmarksql5.0-for-mysql/run"

    os.chdir(path)


    setting_file = "/home/shy/benchmarksql5.0-for-mysql/run/props.conf"
    run_tpcc = "/home/shy/benchmarksql5.0-for-mysql/run/runBenchmark.sh " + setting_file + " >>result.txt"
    os.system(run_tpcc)

def change_governor(governor: str):
    for i in range(1):
        print("change governot to " + governor)
        os.system('ssh ' + 'agent' + str(i + 1) + ' "cpupower frequency-set -g ' + governor + ' 1>/dev/null"')


def cpu_set():
    for i in range(1):
        os.system('ssh ' + 'agent' + str(i + 1) + ' "echo 1 > /sys/fs/cgroup/cpu/user.slice/cpu.dynamic_affinity_mode"')


def cpu_unset():
    for i in range(1):
        os.system('ssh ' + 'agent' + str(i + 1) + ' "echo 0 > /sys/fs/cgroup/cpu/user.slice/cpu.dynamic_affinity_mode"')

def disable_mpc():
    os.system('ssh -f ' + 'agent1' + ' ipmitool raw 0x30 0x93 0xdb 0x07 0x00 0x5a 0x33 0x00 0x01 0x00 0x00')


def enable_mpc():
    os.system('ssh -f ' + 'agent1' + ' ipmitool raw 0x30 0x93 0xdb 0x07 0x00 0x5a 0x33 0x00 0x01 0x00 0x01')


def get_tpcc_scores():
    file = "/home/shy/benchmarksql5.0-for-mysql/run/result.txt"

    with open(file, "r") as input_file:

        str = input_file.readlines()
    for lines in str:
        if "NewOrders" in lines:
            list = lines.split('=')

            tpcc_score = list[1].strip()

            return float(tpcc_score)


def query_date():
    file = "/home/shy/benchmarksql5.0-for-mysql/run/result.txt"
    star_time = os.system("cat file |grep Start|awk -F '=' '{print $2}'")
    end_time = os.system("cat file |grep End|awk -F '=' '{print $2}'")




def clear_cache():
    os.system('echo 3 > /proc/sys/vm/drop_caches')

def change_to_seep():
    for i in range(2):
        os.system('ssh ' + 'agent' + str(i + 1) + ' "echo 1 > /sys/devices/system/cpu/cpufreq/conservative/fast_mode"')


def disable_seep():
    for i in range(2):
        os.system('ssh ' + 'agent' + str(i + 1) + ' "echo 0 > /sys/devices/system/cpu/cpufreq/conservative/fast_mode"')



def set_load():
    os.system("cp /home/shy/benchmarksql5.0-for-mysql/run/props.conf.bak /home/shy/benchmarksql5.0-for-mysql/run/props.conf")
    str1 = "terminals=" + str(size)
    os.system('echo "' + str1 + '" >> /home/shy/benchmarksql5.0-for-mysql/run/props.conf')


if __name__ == '__main__':
    governor_list = ["performance", "conservative"]
    count = 0
    size_list = ['15','20','30','50','60']

    while (1):
        size = size_list[int(count / len(governor_list)) % len(size_list)]
        print(size)
        #
        index = count % len(governor_list)
        governor = governor_list[index]
        change_governor(governor)

        if governor != 'performance':
            governor += str(index)
            change_to_seep()
            cpu_set()
        else:
            cpu_unset()

        print("start tpcc test")

        set_load()
        run_power()
        run_mysql_tpcc()
        os.chdir("/home/shy")


        print("tpcc test finish")
        get_server_data()

        server_power = get_avg_power('power_server.txt')
        server_util = get_avg_util('mpstat_server.txt')
        client_power = get_avg_power('power_client.txt')
        client_util = get_avg_util('mpstat_client.txt')
        tpcc_score = get_tpcc_scores()

        write_csv(governor, server_power, server_util, tpcc_score)

        os.system("rm -rf /home/shy/benchmarksql5.0-for-mysql/run/result.txt")

        clear_cache()

        count += 1
        if count >= 50:
            break
